package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import entity.GoodsImg;
import service.GoodsImgService;

/**
 * Servlet implementation class UploadImgMutiServlet
 */
@WebServlet("/UploadImgMutiServlet")
@MultipartConfig(  
        maxFileSize = 8388608,//最大上传文件大小 
        fileSizeThreshold = 819200,//当数据量大于该值时，内容将被写入文件。
        maxRequestSize =  -1 //针对该 multipart/form-data 请求最大数量，默认值为 -1，表示没有限制。以字节为单位。  
)
public class UploadImgMutiServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	GoodsImgService giService = new GoodsImgService();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadImgMutiServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int goodId = Integer.parseInt(request.getParameter("goodList"));
		List<GoodsImg> goodsImgList = new ArrayList<>();
		
		//获取所有的part
		Collection<Part> parts = request.getParts();
		//使用循环遍历part对象
		for(Part p : parts) {
			String dispo = p.getHeader("content-disposition");
			//获取文件名开始的位置
			int begin = dispo.indexOf("filename=")+10;
			//获取文件名结束的位置
			int end = dispo.lastIndexOf("\"");
			//利用字符串截取，截取真正的文件名
			String fileName = dispo.substring(begin, end);
			Pattern pattern = Pattern.compile("filename=\".+\"");  
			Matcher matcher = pattern.matcher(dispo);  
            if(matcher.find()){  
                fileName = matcher.group(); 
                fileName = fileName.substring(10, fileName.length()-1); 
                String basePath = this.getServletContext().getRealPath("\\");   //获取系统路径
                String path = basePath + "\\postImg\\" + fileName;    // 保存至服务器
                p.write(path);
                GoodsImg goodsImg = new GoodsImg("\\postImg\\" + fileName);
                goodsImgList.add(goodsImg);
            }
            
		}
		giService.addGoodsImg(goodId, goodsImgList);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
